//
//  JITAMainView.m
//  JITAsound
//
//  Created by tikeios_002 on 2023/11/4.
//

#import "JITAMainView.h"
#import "JITALineCell.h"
#import <AudioToolbox/AudioToolbox.h>
#import "WT_HZ.h"
#import <AVFoundation/AVFoundation.h>
@interface JITAMainView ()<UICollectionViewDelegate,UICollectionViewDataSource,AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *lineCollection;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine1;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine2;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine3;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine4;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine5;
@property (weak, nonatomic) IBOutlet UIImageView *JITALine6;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton1;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton2;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton3;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton4;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton5;
@property (weak, nonatomic) IBOutlet UIButton *JITAButton6;
@property (weak, nonatomic) IBOutlet UIImageView *JITAOkImage;
@property (weak, nonatomic) IBOutlet UIImageView *JITAErrImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *JITAErrLeft;

@property (strong ,nonatomic)AVAudioPlayer * audioPlayer;
@property (assign ,nonatomic) BOOL isVideoPlay;
@property (assign ,nonatomic)CGFloat lineWidth;
@property (strong ,nonatomic)NSArray *HZArray;
@property (strong ,nonatomic)NSArray *ValueArr;
@property (assign ,nonatomic)CGFloat minValue;
@property (assign ,nonatomic)CGFloat nowValue;
@property (assign ,nonatomic)CGFloat maxValue;
@property (assign ,nonatomic)CGFloat videoShowWidth;
@property (assign ,nonatomic)int jsNum;
@end

@implementation JITAMainView

- (void)viewDidLoad {
    [super viewDidLoad];
    self.JITAButton1.layer.cornerRadius = 20;
    self.JITAButton2.layer.cornerRadius = 20;
    self.JITAButton3.layer.cornerRadius = 20;
    self.JITAButton4.layer.cornerRadius = 20;
    self.JITAButton5.layer.cornerRadius = 20;
    self.JITAButton6.layer.cornerRadius = 20;
    [self.view bringSubviewToFront:self.lineCollection];
    [self.view bringSubviewToFront:self.JITAErrImage];
    [self.view bringSubviewToFront:self.JITAOkImage];
    _lineWidth = (KScreen_W-56.2)/20;
    _videoShowWidth = (KScreen_W-30)/2;
    [self.lineCollection registerNib:[UINib nibWithNibName:@"JITALineCell" bundle:nil] forCellWithReuseIdentifier:@"JITALineCell"];
    self.lineCollection.delegate = self;
    self.lineCollection.dataSource = self;
    _ValueArr = [[NSArray alloc]initWithObjects:@"146.832",@"110.000",@"82.407",@"195.998",@"246.942",@"329.628", nil];
    _HZArray = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"HZArray" ofType:@"plist"]];
}
- (IBAction)JITAClick:(UIButton *)sender {
    [self HideChangeView];
    if(sender.selected){

    }else{
        if(sender.tag == 0){
            self.JITALine1.hidden = NO;
            [self PlayAudio:@"ic_video_d4"];
        }else if(sender.tag == 1){
            self.JITALine2.hidden = NO;
            [self PlayAudio:@"ic_video_a3"];
        }else if(sender.tag == 2){
            self.JITALine3.hidden = NO;
            [self PlayAudio:@"ic_video_e3"];
        }else if(sender.tag == 3){
            self.JITALine4.hidden = NO;
            [self PlayAudio:@"ic_video_g4"];
        }else if(sender.tag == 4){
            self.JITALine5.hidden = NO;
            [self PlayAudio:@"ic_video_b4"];
        }else if(sender.tag == 5){
            self.JITALine6.hidden = NO;
            [self PlayAudio:@"ic_video_e4"];
        }
        float a = [_ValueArr[sender.tag] floatValue];
        for (int i=0; i<_HZArray.count; i++) {
            if (a == [_HZArray[i] floatValue]) {
                _minValue = [_HZArray[i-1] floatValue];
                _nowValue = a;
                _maxValue = [_HZArray[i+1] floatValue];
                break;
            }
        }
        
        sender.layer.borderWidth = 1;
        sender.layer.borderColor = RGB(245, 0, 204).CGColor;
        
        /**
         *
         *  检测声音频率的核心
         *
         *  将检测到的声音频率，通过HZArray.plist和standerd_note.plist对应的声音频率表，翻译成对应的音调
         */
        // initialize stuff
        _jsNum = 0;
        [WTHZ creatWTAudio];
        [WTHZ startWTAudioCallBack:^(float MAX_HZ) {
            [self changeUIWithHZParmaters:MAX_HZ];
        }];
    }
    sender.selected = !sender.selected;
}
- (void)HideChangeView{
    self.JITALine1.hidden = YES;
    self.JITALine2.hidden = YES;
    self.JITALine3.hidden = YES;
    self.JITALine4.hidden = YES;
    self.JITALine5.hidden = YES;
    self.JITALine6.hidden = YES;
    self.JITAButton1.selected = NO;
    self.JITAButton1.layer.borderWidth = 0;
    self.JITAButton2.selected = NO;
    self.JITAButton2.layer.borderWidth = 0;
    self.JITAButton3.selected = NO;
    self.JITAButton3.layer.borderWidth = 0;
    self.JITAButton4.selected = NO;
    self.JITAButton4.layer.borderWidth = 0;
    self.JITAButton5.selected = NO;
    self.JITAButton5.layer.borderWidth = 0;
    self.JITAButton6.selected = NO;
    self.JITAButton6.layer.borderWidth = 0;
}

#pragma mark - UICollectionView data source

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 21;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    JITALineCell * JITACell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JITALineCell" forIndexPath:indexPath];
    if(indexPath.row%5 != 0){
        JITACell.cellLineWdiht.constant = 1;
        JITACell.cellLineHeight.constant = 58;
        JITACell.cellLine.backgroundColor = RGB(208, 208, 208);
    }else{
        JITACell.cellLineWdiht.constant = 2;
        JITACell.cellLineHeight.constant = 88;
        if(indexPath.row == 10){
            JITACell.cellLine.backgroundColor = RGB(0, 244, 169);
        }else{
            JITACell.cellLine.backgroundColor = RGB(208, 208, 208);
        }
    }
    return JITACell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row%5 != 0){
        return CGSizeMake(1, 58);
    }else{
        return CGSizeMake(2, 88);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
 layout:(UICollectionViewLayout *)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.lineWidth;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.lineWidth;
}
#pragma mark 点击事件
-(void)PlayAudio:(NSString *)name{
    _isVideoPlay = YES;
    NSString* soundFilePath;
    soundFilePath =[[NSBundle mainBundle]pathForResource:name ofType:@"mp3"];
    NSURL*soundURL = [NSURL fileURLWithPath:soundFilePath];
    // 初始化播放器，注意这里的Url参数只能为本地文件路径，不支持HTTP Url
    NSError *error = nil;
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:&error];
    _audioPlayer.delegate = self;
    //设置播放器属性
    _audioPlayer.numberOfLoops = 0;// 不循环
    _audioPlayer.volume = 1; // 音量
    [_audioPlayer prepareToPlay];// 加载音频文件到缓存【这个函数在调用play函数时会自动调用】
   
    if(error){
      NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
  
    }
    [_audioPlayer play];
    
   
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    _isVideoPlay = NO;
}
- (void)changeUIWithHZParmaters:(float)MAX_HZ {
    if (_isVideoPlay) {
        return;
    }
    if (MAX_HZ<50 || MAX_HZ>600) {
        return;
    }
    if (_nowValue-(_nowValue-_minValue)*0.17 < MAX_HZ && _nowValue+(_maxValue-_nowValue)*0.17 > MAX_HZ) {
        _jsNum = _jsNum+1;
        _JITAOkImage.hidden = NO;
        _JITAErrImage.hidden = YES;
        if (_jsNum == 1) {
            [self PlayAudio:@"bingo"];
        }
    }else{
        _JITAOkImage.hidden = YES;
        _JITAErrImage.hidden = NO;
        if (_nowValue > MAX_HZ) {
            float pj = (_nowValue-_minValue)/2;
            if (MAX_HZ < _minValue+pj) {
                _JITAErrImage.image = KImageNamed(@"ic_jita_zuidi");
            }else{
                _JITAErrImage.image = KImageNamed(@"ic_jita_pindi");
            }
            
        }else{
            float pj = (_maxValue-_nowValue)/2;
            if (MAX_HZ < _nowValue+pj) {
                _JITAErrImage.image = KImageNamed(@"ic_jita_pingao");
            }else{
                _JITAErrImage.image = KImageNamed(@"ic_jita_zuigao");
            }
        }
        if(MAX_HZ < _minValue){
            _JITAErrLeft.constant = 0;
        }else if (MAX_HZ > _minValue){
            _JITAErrLeft.constant = KScreen_W-22;
        }else{
            float a = (_maxValue-MAX_HZ)/(_maxValue-_minValue);
            float x = a*(KScreen_W-30)+4;
            _JITAErrLeft.constant = x;
        }
    }
}
@end
